import * as XLSX from 'xlsx-js-style'
import { useMessage } from '@/hooks/web/useMessage'
import { formatDate } from '@/utils/formatTime'
export const useExportRecipeExcel = () => {
  const message = useMessage()
  // 页面设置常量
  const PAGE_SETUP = {
    paperSize: 9 as const, // A4
    orientation: 'landscape' as const, // 横向
    fitToPage: true,
    fitToWidth: 1,
    fitToHeight: 1, // 强制适应一页高
    horizontalCentered: true,
    margins: {
      left: 0.3,
      right: 0.3,
      top: 0.3,
      bottom: 0.3,
      header: 0.0,
      footer: 0.0
    }
  }

  // 定义样式
  const styles = {
    // 标题样式
    title: {
      font: {
        sz: 14,
        bold: true,
        color: { rgb: '000000' }
      },
      alignment: {
        vertical: 'center',
        horizontal: 'center'
      },
      border: {
        top: { style: 'thin', color: { rgb: '000000' } },
        bottom: { style: 'thin', color: { rgb: '000000' } },
        left: { style: 'thin', color: { rgb: '000000' } },
        right: { style: 'thin', color: { rgb: '000000' } }
      }
    },
    // 表头样式（居左对齐）
    headerLeft: {
      font: {
        sz: 10,
        bold: true,
        color: { rgb: '000000' }
      },
      alignment: {
        vertical: 'center',
        horizontal: 'left'
      },
      fill: {
        fgColor: { rgb: 'EFEFEF' }
      },
      border: {
        top: { style: 'thin', color: { rgb: '000000' } },
        bottom: { style: 'thin', color: { rgb: '000000' } },
        left: { style: 'thin', color: { rgb: '000000' } },
        right: { style: 'thin', color: { rgb: '000000' } }
      }
    },
    // 表头样式（居中对齐）
    headerCenter: {
      font: {
        sz: 10,
        bold: true,
        color: { rgb: '000000' }
      },
      alignment: {
        vertical: 'center',
        horizontal: 'center'
      },
      fill: {
        fgColor: { rgb: 'EFEFEF' }
      },
      border: {
        top: { style: 'thin', color: { rgb: '000000' } },
        bottom: { style: 'thin', color: { rgb: '000000' } },
        left: { style: 'thin', color: { rgb: '000000' } },
        right: { style: 'thin', color: { rgb: '000000' } }
      }
    },
    // 数据样式（居左对齐）
    dataLeft: {
      font: {
        sz: 9,
        bold: false,
        color: { rgb: '000000' }
      },
      alignment: {
        vertical: 'center',
        horizontal: 'left'
      },
      border: {
        top: { style: 'thin', color: { rgb: '000000' } },
        bottom: { style: 'thin', color: { rgb: '000000' } },
        left: { style: 'thin', color: { rgb: '000000' } },
        right: { style: 'thin', color: { rgb: '000000' } }
      }
    },
    // 数据样式（居中对齐）
    dataCenter: {
      font: {
        sz: 9,
        bold: false,
        color: { rgb: '000000' }
      },
      alignment: {
        vertical: 'center',
        horizontal: 'center'
      },
      border: {
        top: { style: 'thin', color: { rgb: '000000' } },
        bottom: { style: 'thin', color: { rgb: '000000' } },
        left: { style: 'thin', color: { rgb: '000000' } },
        right: { style: 'thin', color: { rgb: '000000' } }
      }
    }
  }
  // 格式化重量，将克转换为斤
  const formatWeight = (weightInGrams: number): string => {
    // 1斤 = 500克
    return (weightInGrams / 500).toFixed(2)
  }
  // 最终完善版导出函数
  const exportRecipeExcel = (displayedWeekDays: any[], tableData: any[], weeklyData: any) => {
    try {
      // 获取数据行
      const peopleRow = tableData.find((row) => row.type === 'people')
      const deliveryTimeRow = tableData.find((row) => row.type === 'deliveryTime')
      const ingredientsRow = tableData.find((row) => row.type === 'ingredients')

      if (!peopleRow || !deliveryTimeRow || !ingredientsRow) {
        message.error('数据不完整，无法导出')
        return
      }

      // 创建工作簿
      const wb = XLSX.utils.book_new()

      // 创建工作表数据
      const wsData: any[][] = []

      // 1. 标题行 (合并单元格)
      const titleDate = `${weeklyData.weekYear}年第${weeklyData.weekNumber} ${formatDate(weeklyData.weekStartDate, 'YYYY-MM-DD')}-${formatDate(weeklyData.weekEndDate, 'YYYY-MM-DD')}`
      wsData.push([`食材采购清单 (${titleDate})`])

      // 2. 日期行
      const dateRow: any[] = []
      displayedWeekDays.forEach((day) => {
        const dateText = day.date ? `${day.label}(${day.date})` : day.label
        dateRow.push(dateText, '') // 每个日期占两列
      })
      wsData.push(dateRow)

      // 3. 用餐人数行（添加前缀）
      const peopleDataRow: any[] = []
      displayedWeekDays.forEach((day) => {
        peopleDataRow.push(`人数：${peopleRow[`day${day.value}`] || 0}`, '')
      })
      wsData.push(peopleDataRow)

      // 4. 配送时间行（添加前缀）
      const deliveryTimeDataRow: any[] = []
      displayedWeekDays.forEach((day) => {
        const deliveryTime = deliveryTimeRow[`day${day.value}`]
        const formattedTime = deliveryTime
          ? formatDate(new Date(deliveryTime), 'YYYY-MM-DD HH:mm')
          : ''
        deliveryTimeDataRow.push(`配送时间：${formattedTime}`, '')
      })
      wsData.push(deliveryTimeDataRow)

      // 5. 食材名称和重量标题行
      const headerRow: any[] = []
      displayedWeekDays.forEach(() => {
        headerRow.push('食材名称', '重量')
      })
      wsData.push(headerRow)

      // 6. 添加食材数据
      // 获取所有日期中最大的食材数量
      let maxIngredientCount = 0
      const ingredientsByDay: Record<number, any[]> = {}

      displayedWeekDays.forEach((day) => {
        const ingredients = ingredientsRow[`day${day.value}`] || []
        ingredientsByDay[day.value] = ingredients
        if (ingredients.length > maxIngredientCount) {
          maxIngredientCount = ingredients.length
        }
      })

      // 添加食材数据行
      for (let i = 0; i < maxIngredientCount; i++) {
        const row: any[] = []

        displayedWeekDays.forEach((day) => {
          const ingredients = ingredientsByDay[day.value]
          if (i < ingredients.length) {
            const item = ingredients[i]
            row.push(item.foodName, `${formatWeight(item.usage)}斤`)
          } else {
            row.push('', '')
          }
        })

        wsData.push(row)
      }

      // 创建工作表
      const ws = XLSX.utils.aoa_to_sheet(wsData)

      // 设置合并单元格
      const merges: XLSX.Range[] = []
      const daysCount = displayedWeekDays.length

      // 1. 标题行合并 (第一行合并所有列)
      merges.push({
        s: { r: 0, c: 0 },
        e: { r: 0, c: daysCount * 2 - 1 }
      })

      // 2. 日期行合并（每个日期下的两列合并）
      displayedWeekDays.forEach((day, index) => {
        merges.push({
          s: { r: 1, c: index * 2 },
          e: { r: 1, c: index * 2 + 1 }
        })
      })

      // 3. 用餐人数行合并
      displayedWeekDays.forEach((day, index) => {
        merges.push({
          s: { r: 2, c: index * 2 },
          e: { r: 2, c: index * 2 + 1 }
        })
      })

      // 4. 配送时间行合并
      displayedWeekDays.forEach((day, index) => {
        merges.push({
          s: { r: 3, c: index * 2 },
          e: { r: 3, c: index * 2 + 1 }
        })
      })

      ws['!merges'] = merges

      // 设置列宽以适应A4横向打印
      const colWidths: any = []

      // 为每个日期设置两列宽度
      displayedWeekDays.forEach(() => {
        colWidths.push({ wch: 16 }) // 食材名称列
        colWidths.push({ wch: 7 }) // 重量列
      })

      ws['!cols'] = colWidths

      // 应用样式
      // 1. 标题行样式（确保所有单元格都有边框）
      for (let C = 0; C < daysCount * 2; ++C) {
        const cellAddress = XLSX.utils.encode_cell({ r: 0, c: C })
        if (!ws[cellAddress]) {
          // 创建空单元格以确保边框显示
          ws[cellAddress] = { t: 's', v: '' }
        }
        ws[cellAddress].s = styles.title
      }

      // 2. 表头行样式（日期行）
      for (let C = 0; C < daysCount * 2; ++C) {
        const cellAddress = XLSX.utils.encode_cell({ r: 1, c: C })
        if (!ws[cellAddress]) continue
        ws[cellAddress].s = styles.headerCenter
      }

      // 3. 用餐人数行样式
      for (let C = 0; C < daysCount * 2; ++C) {
        const cellAddress = XLSX.utils.encode_cell({ r: 2, c: C })
        if (!ws[cellAddress]) continue
        ws[cellAddress].s = styles.dataCenter
      }

      // 4. 配送时间行样式
      for (let C = 0; C < daysCount * 2; ++C) {
        const cellAddress = XLSX.utils.encode_cell({ r: 3, c: C })
        if (!ws[cellAddress]) continue
        ws[cellAddress].s = styles.dataCenter
      }

      // 5. 食材标题行样式（居左对齐）
      for (let C = 0; C < daysCount * 2; ++C) {
        const cellAddress = XLSX.utils.encode_cell({ r: 4, c: C })
        if (!ws[cellAddress]) continue

        // 奇数列为食材名称（居左），偶数列为重量（居左）
        if (C % 2 === 0) {
          ws[cellAddress].s = styles.headerLeft
        } else {
          ws[cellAddress].s = styles.headerLeft
        }
      }

      // 6. 食材数据行样式（居左对齐）
      for (let i = 0; i < maxIngredientCount; i++) {
        const rowNum = 5 + i // 从第6行开始（索引从0开始）

        for (let C = 0; C < daysCount * 2; ++C) {
          const cellAddress = XLSX.utils.encode_cell({ r: rowNum, c: C })
          if (!ws[cellAddress]) continue

          // 奇数列为食材名称（居左），偶数列为重量（居左）
          if (C % 2 === 0) {
            ws[cellAddress].s = styles.dataLeft
          } else {
            ws[cellAddress].s = styles.dataLeft
          }
        }
      }

      // 设置页面布局为A4横向
      ws['!printGrid'] = true
      ws['!pageSetup'] = PAGE_SETUP

      // 添加工作表到工作簿
      XLSX.utils.book_append_sheet(wb, ws, '食材采购清单')

      // 生成文件并下载
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
      const blob = new Blob([wbout], { type: 'application/octet-stream' })

      const filename = `食材采购清单_${titleDate}.xlsx`
      // download.file(URL.createObjectURL(blob), filename);
      XLSX.writeFile(wb, filename)
      message.success('导出成功')
    } catch (error) {
      console.error('导出失败:', error)
      message.error('导出失败')
    }
  }
  return {
    formatWeight,
    exportRecipeExcel
  }
}
